import re

from pymysql import IntegrityError
from sqlalchemy.exc import  DBAPIError


class ValidationError(ValueError):
    pass


class FieldError(ValueError):
    pass


def handle_mysqlError(error):

    if error.orig and  isinstance(error.orig,IntegrityError):
        code = error.orig.args[0]
        if code == 1062:

            msg = error.orig.args[1]
            rs = re.match(r".*(\s[\\\'|\'](\w*)[\\\'|\']\s)+.*",msg)
            field = rs.group(2) if rs else None
            msg = "字段值[{field}]不能重复".format(field=field)
        else:
            msg = error.orig.args[1]
            print(msg)
        return str(msg)
    pass


def handler(error):

    t  = type(error)
    if isinstance(error,DBAPIError):
        return handle_mysqlError(error)
    return "unknown error"
    pass